package cz.data.gateway.model.utils;

import cz.data.gateway.model.dto.FilterDefinitionDto;
import cz.data.gateway.model.dto.PredicateDefinitionDto;
import cz.data.gateway.model.dto.RouteDefinitionDto;

import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RouteDefinitionUtils {

    public static RouteDefinitionDto createRouteDefinition(String id, String serviceName, String method, String prefixPath) {
        return createRouteDefinition(id, serviceName, method, prefixPath, 0);
    }

    public static RouteDefinitionDto createRouteDefinition(String id, String serviceName, String method, String prefixPath, int parts) {
        RouteDefinitionDto route = new RouteDefinitionDto();
        route.setId(id);
        route.setRouteId(id);
        route.setUri(URI.create("lb://" + serviceName));
        List<PredicateDefinitionDto> predicates = new ArrayList<>();
        predicates.add(createPredicateDefinition(prefixPath));
        if (method != null) {
            predicates.add(createMethodPredicateDefinition(method));
        }
        route.setPredicates(predicates);
        route.setFilters(Collections.singletonList(createFilterDefinition(parts)));
        return route;
    }

    public static PredicateDefinitionDto createPredicateDefinition(String prefixPath) {
        PredicateDefinitionDto predicate = new PredicateDefinitionDto();
        predicate.setName("Path");
        Map<String, Object> args = new HashMap<>();
        args.put("prefix", prefixPath);
        predicate.setArgs(args);
        return predicate;
    }

    public static PredicateDefinitionDto createMethodPredicateDefinition(String method) {
        PredicateDefinitionDto predicate = new PredicateDefinitionDto();
        predicate.setName("Method");
        Map<String, Object> args = new HashMap<>();
        args.put("methods", Collections.singletonList(method));
        predicate.setArgs(args);
        return predicate;
    }

    public static FilterDefinitionDto createFilterDefinition(int parts) {
        FilterDefinitionDto filter = new FilterDefinitionDto();
        filter.setName("StripPrefix");
        Map<String, String> args = new HashMap<>();
        args.put("parts", String.valueOf(parts));
        filter.setArgs(args);
        return filter;
    }
}
